var Admin = Admin || {};
Admin.isJson = function (obj) {
    return typeof(obj) === "object" && Object.prototype.toString.call(obj).toLowerCase() === "[object object]" && !obj.length;
};

Admin.ajax = {};
Admin.ajax.request = function ($this, method, option) {
    var options = $.extend({type: 'json'}, option);
    var text = $this.attr('title') || $this.data('original-title') || $this.val() || $this.text();

    $.ajax({
        type: method,
        url: options.url || $this.attr('href'),
        data: options.data,
        dataType: options.type,
        context: $this,
        beforeSend: options.beforeSend || function () {
            $.jBox.tip('正在' + text + '...', 'loading');
        },
        error: options.error || function (jqXHR, statusText, error) {
            var title = typeof error === 'object' ? statusText : error;
            window.setTimeout(function () {
                $.jBox.closeTip();
            }, 1000);
            window.setTimeout(function () {
                var text = jqXHR.responseText;
                text = text.replace('<pre>', '<div style="white-space: pre;margin-bottom: 15px;overflow: auto;">');
                text = text.replace('</pre>', '</div>');
                $.jBox(text, {title: title, width: 500});
            }, 1500);
        },
        success: options.success || function (result) {
            if (!Admin.isJson(result)) {
                window.setTimeout(function () {
                    $.jBox.tip(text + result, 'error');
                }, 1500);
                return;
            }
            if (result.code === 0) {
                var msg = result['msg'] || (text + '成功');
                window.setTimeout(function () {
                    $.jBox.tip(msg, 'success');
                }, 1500);
                window.setTimeout(function () {
                    var redirect = $this.attr('redirect') || result['redirect'] || false;
                    if (redirect) {
                        window.location.href = redirect;
                    } else {
                        window.location.reload();
                    }
                }, 2000);
                return;
            }
            window.setTimeout(function () {
                $.jBox.tip(result['msg'], 'error');
            }, 1500);
        }
    });
};

Admin.ajax.get = function ($this, options) {
    Admin.ajax.request($this, 'GET', options);
};

Admin.ajax.post = function ($this, option) {
    var options = option || {};
    if (!options.data && !options.url) {
        var form = $this.parents('form');
        var url = form.attr('action');
        var data = form.serialize();
        options = $.extend({'data': data, 'url': url}, options);
    }
    Admin.ajax.request($this, 'POST', options);
};

(function ($) {
    $.fn.ajaxGet = function (options) {
        return this.each(function () {
            Admin.ajax.get($(this), options);
        });
    };
})(jQuery);

(function ($) {
    $.fn.ajaxPost = function (options) {
        return this.each(function () {
            Admin.ajax.post($(this), options);
        });
    };
})(jQuery);

(function ($) {

    $('.menu li').click(function () {
        $(this).toggleClass('open').find('.sub-menu').slideToggle();
    });

    $(document).on('click', '.dialog', function () {
        var $this = $(this);
        if ($this.hasClass('disabled')) {
            return false;
        }
        var _buttons = $this.data('buttons');
        if (_buttons) {
            _buttons = eval('(' + _buttons + ')');
        }
        var options = {
            title: $this.attr('title') || $this.data('original-title') || $this.text() || $this.val(),
            buttons: _buttons || {'保存': 'save', '取消': 'cancel'},
            width: $this.data('width') || 500,
            height: $this.data('height') || 'auto',
            submit: function (v, h, f) {
                if (v === 'save') {
                    h.find(':submit').trigger('click');
                    return false;
                }
                return true;
            }
        };
        var href = $this.attr('href') || $this.data('href');
        $.jBox('get:' + href, options);
        return false;
    });

    $(document).on('click', '.view', function () {
        var $this = $(this);
        if ($this.hasClass('disabled')) {
            return false;
        }
        var href = $this.attr('href') || $this.data('href');
        var options = {
            title: $this.attr('title') || $this.data('original-title') || $this.text() || $this.val(),
            buttons: {'关闭': 'cancel'},
            width: $this.data('width') || 500,
            height: $this.data('height') || 'auto'
        };
        $.jBox('get:' + href, options);
        return false;
    });

    $(document).on('click', '.get', function () {
        var $this = $(this);
        if ($this.hasClass('disabled')) {
            return false;
        }
        $this.ajaxGet();
        return false;
    });

    $(document).on('click', '.delete', function () {
        var $this = $(this);
        if ($this.hasClass('disabled') || $this.hasClass('batch')) {
            return false;
        }
        var title = $this.attr('title') || $this.data('original-title') || $this.val() || $this.text();
        var content = $this.data('content') || ('确定' + title + '?');
        var submit = function (v, h, f) {
            if (v === 'danger') {
                $this.ajaxGet();
            }
            return true;
        };
        $.jBox.confirm(content, title, submit, {buttons: {'删除': 'danger', '取消': 'cancel'}});
        return false;
    });

    $(document).on('click', '.confirm', function () {
        var $this = $(this);
        var title = $this.attr('title') || $this.data('original-title') || $this.val() || $this.text();
        var content = $this.data('content') || ('确定' + title + '?');
        var submit = function (v, h, f) {
            if (v === 'save') {
                $this.ajaxGet();
            }
            return true;
        };
        $.jBox.confirm(content, title, submit, {buttons: {'确定': 'save', '取消': 'cancel'}});
        return false;
    });

    $('[data-toggle="tooltip"]').tooltip();

    $('.hint-block').each(function () {
        var $hint = $(this);
        $hint.parent().find('input, textarea').attr('placeholder', $hint.html());
        // $hint.parent().find('label').addClass('help').popover({
        //     html: true,
        //     trigger: 'hover',
        //     placement: 'right',
        //     content: $hint.html()
        // });
    });
})(jQuery);

$(function () {
    $(document).on('afterValidateAttribute', 'form', function (event, attribute, message) {
        var $form = $(this);
        var $error = $form.find(attribute.container).find(attribute.error);
        var px = message.length > 0 ? '-10px' : 0;
        $error.css('margin-bottom', px);
        return false;
    });

    $(document).on('beforeSubmit', 'form', function () {
        var form = $(this);
        if (form.find('.has-error').length) {
            return false;
        }
        form.find(':submit').ajaxPost();
        return false;
    });
});

$(function () {
    $('.empty').parent('td').css('border-bottom', 'none');

    $('.glyphicon-search').on('click', function () {
        $(this).parent('form').submit();
    });

    $('.search input[name="wd"]').on('keypress', function (event) {
        if (event.keyCode == 13) {
            $(this).parent('form').submit();
        }
    });

    if (typeof highcharts != 'undefined' && Admin.isJson(highcharts) && highcharts.ts.length) {
        $('#highcharts').highcharts({
            title: {text: highcharts.name, x: -20},
            xAxis: {categories: highcharts.ts},
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
                borderWidth: 0
            },
            series: highcharts.data
        });
    }
});